//
//  JYTabBarController.m
//  FinderBox
//
//  Created by JiYi on 2018/10/11.
//  Copyright © 2018 JiYi. All rights reserved.
//

#import "JYTabBarController.h"

#import "JYTabBar.h"

@interface JYTabBarController ()

@property (nonatomic, strong) JYBaseWebViewController * home;
@property (nonatomic, strong) JYBaseWebViewController * se;
@property (nonatomic, strong) JYBaseWebViewController * bss;
@property (nonatomic, strong) JYBaseWebViewController * me;



@end

@implementation JYTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    JYTabBar *baseTabBar = [[JYTabBar alloc] init];
    [self setValue:baseTabBar forKey:@"tabBar"];
    
}
- (instancetype)init {
    if (self == [super init]) {
        [self loadCachePage];
    }
    return self;
}

#pragma mark - 动态加载
- (void)loadCachePage {
    YYCache * cache = [YYCache cacheWithName:kJYAppVersionData];
    if ([cache containsObjectForKey:@"kJYAppVersionData"]) {
        NSString * appdata = (NSString *)[cache objectForKey:@"kJYAppVersionData"];
        
        if (appdata.length == 0) {
            [self getData];
        }else {
            //  has cache, continue loading
            //  判断时间是否过期
            NSDate * nowDate = [NSDate date];
            NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[nowDate timeIntervalSince1970]];
            //  毫秒
            if (appdata.integerValue < timeStr.integerValue) {
                //  过期
                [self getData];
            }else {
                //  正常加载
                [self customload];
            }
        }
    }else {
        //  no cache, get data
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self setdataWithLocal];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadRootVC" object:nil];
        });
    }
}

#pragma mark - 正常加载
- (void)customload {
    YYCache * cache = [YYCache cacheWithName:kJYAppVersionData];
    id idmm = [cache objectForKey:@"tabData"];
    if (idmm) {
        NSMutableArray * titleArr = [NSMutableArray array];
        NSMutableArray * classArr = [NSMutableArray array];
        NSMutableArray * flagArr = [NSMutableArray array];
        NSMutableArray * imageArr = [NSMutableArray array];
        NSMutableArray * imageSLArr = [NSMutableArray array];
        NSMutableArray * urlLArr = [NSMutableArray array];
        
        NSString * pushK = [NSString string];
        
        for (NSDictionary * tempDict in idmm) {
            [titleArr addObject:tempDict[@"titleStr"]];
            [classArr addObject:tempDict[@"classStr"]];
            [flagArr addObject:tempDict[@"flag"]];
            [imageArr addObject:tempDict[@"imageStr"]];
            [imageSLArr addObject:tempDict[@"image_slStr"]];
            [urlLArr addObject:tempDict[@"urlStr"]];
            pushK = tempDict[@"key"];
        }
        
        if (pushK.length !=0 && ![pushK isEqualToString:@"0"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PPPushKey" object:pushK];
        }
        
        NSMutableArray * views = [NSMutableArray array];
        int i = 0;
        for (NSString * classStr in classArr) {

            UIViewController * vc = nil;
            if ([classStr isEqualToString:@"JYSportPlanViewController"]) {
                vc = [[UIStoryboard storyboardWithName:@"JYSportPlanViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"JYSportPlanViewController"];
            }else {
                vc = [[NSClassFromString(classStr) alloc] init];
            }
            JYNavigationController * navVC = [[JYNavigationController alloc] initWithRootViewController:vc];
            navVC.title = titleArr[i];
            navVC.tabBarItem.title = titleArr[i];
            vc.title = titleArr[i];
            vc.urlStr = urlLArr[i];
            [navVC.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                      [UIFont systemFontOfSize:13],NSFontAttributeName,
                                                      JYMainColor,NSForegroundColorAttributeName,
                                                      nil] forState:UIControlStateSelected];
            [navVC.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                      [UIFont systemFontOfSize:13], NSFontAttributeName,
                                                      [UIColor lightGrayColor],NSForegroundColorAttributeName,
                                                      nil] forState:UIControlStateNormal];
            [navVC.tabBarItem zy_setImageWithURL:imageArr[i] withImage:[UIImage imageNamed:imageArr[i]]];
            [navVC.tabBarItem zy_setSelectImageWithURL:imageSLArr[i] withImage:[UIImage imageNamed:imageSLArr[i]]];
            
            [views addObject:navVC];
            
            i++;
        }
        self.viewControllers = views;
    }
}



#pragma mark - getData
- (void)getData {
    AVObject *todo =[AVObject objectWithClassName:@"TotalData" objectId:@"5bbef9579f545400701887c7"];
    [todo fetchInBackgroundWithBlock:^(AVObject *avObject, NSError *error) {
        if (!error) {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            

            NSString * lanchTime = avObject[@"data"][@"lanchTime"];
            NSString * pushkey = avObject[@"data"][@"pushkey"];
            NSString * appVersion = avObject[@"data"][@"appVersion"];
            
            NSArray * appVArr = [app_Version componentsSeparatedByString:@"."];
            NSArray * nowVersion = [appVersion componentsSeparatedByString:@"."];
            
            NSInteger flag = 0;
            
            CGFloat appVFloat = 0;
            CGFloat nowVFloat = 0;
            
            for (int i = 0; i < appVArr.count; i++) {
                NSString * str = appVArr[i];
                NSString * tempStr = nowVersion[i];
                if (i == 0) {
                    appVFloat += str.integerValue * 100;
                    nowVFloat += tempStr.integerValue * 100;
                }else if (i == 1) {
                    appVFloat += str.integerValue * 10;
                    nowVFloat += tempStr.integerValue * 10;
                }else {
                    appVFloat += str.integerValue;
                    nowVFloat += tempStr.integerValue;
                }
            }
            
            if (appVFloat <= nowVFloat) {
                flag = 1;
            }
            
            if (flag == 1) {
                YYCache * cache = [YYCache cacheWithName:kJYAppVersionData];
                //  11:22
                [cache setObject:[NSString stringWithFormat:@"%@",lanchTime] forKey:@"kJYAppVersionData"];
                
                NSMutableArray * tempArr = [NSMutableArray array];
                
                NSArray * tabArr = [NSArray yy_modelArrayWithClass:[JYTabBarVCModel class] json:avObject[@"data"][@"data"]];
                for (JYTabBarVCModel * model in tabArr) {
                    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                    [dict setObject:model.title.length == 0 ? @" ":model.title forKey:@"titleStr"];
                    [dict setObject:model.image.length == 0 ? @"1":model.image forKey:@"imageStr"];
                    [dict setObject:model.url.length == 0 ? @[]:model.url forKey:@"urlStr"];
                    [dict setObject:model.image_sl.length == 0 ? @"1":model.image_sl forKey:@"image_slStr"];
                    [dict setObject:model.controller.length == 0 ? @"JYViewController":model.controller forKey:@"classStr"];
                    [dict setObject:pushkey == 0 ? @"0":pushkey forKey:@"keyStr"];
                    
                    
                    if (model.url.length == 0) {
                        [dict setObject:@"0" forKey:@"flag"];
                    }else {
                        [dict setObject:@"1" forKey:@"flag"];
                    }
                    
                    [tempArr addObject:dict];
                }
                
                
                [cache setObject:tempArr forKey:@"tabData"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadRootVC" object:nil];
            }else {
                [self setdataWithLocal];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadRootVC" object:nil];
            }
        }else {
            [self setdataWithLocal];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadRootVC" object:nil];
        }
    }];
}

#pragma mark - 设置本地数据
- (void)setdataWithLocal {
    YYCache * cache = [YYCache cacheWithName:kJYAppVersionData];
    NSDate * nowDate = [NSDate date];
    [cache setObject:[NSString stringWithFormat:@"%.0f",[nowDate timeIntervalSince1970] + 20] forKey:@"kJYAppVersionData"];

    NSMutableArray * tempArr = [NSMutableArray array];
    [tempArr addObject:@{@"titleStr":@"开始运动", @"imageStr":@"运动首页", @"image_slStr":@"运动首页", @"urlStr":@"", @"classStr":@"JYSportViewController",@"flag":@"0"}];
    [tempArr addObject:@{@"titleStr":@"运动历史", @"imageStr":@"历史", @"image_slStr":@"历史", @"urlStr":@"", @"classStr":@"JYSportDailyViewController",@"flag":@"0"}];
    [tempArr addObject:@{@"titleStr":@"运动计划", @"imageStr":@"计划", @"image_slStr":@"计划", @"urlStr":@"", @"classStr":@"JYSportPlanViewController",@"flag":@"0"}];
    [cache setObject:tempArr forKey:@"tabData"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
